package com.zadtek.shopmall.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.zadtek.shopmall.App;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.User;
import com.zadtek.shopmall.other.Const;
import com.zadtek.shopmall.other.UserInfoManger;
import com.zadtek.shopmall.utils.SPUtil;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.dialog.BaseNiceDialog;
import com.zadtek.shopmall.view.dialog.NiceDialog;
import com.zadtek.shopmall.view.dialog.ViewConvertListener;
import com.zadtek.shopmall.view.dialog.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import me.nereo.multi_image_selector.MultiImageSelector;

public class SettingActivity extends AbsActivity implements View.OnClickListener {
    private ImageView ivBack;
    private TextView title;
    private LinearLayout llHeadimg;
    private CircleImageView ivHeadimg;
    private LinearLayout llUsername;
    private TextView tvUsername;
    private LinearLayout llSex;
    private TextView tvSex;
    private LinearLayout llPhonenumber;
    private TextView etPhonenumber;
    private LinearLayout llEmail;
    private TextView etEmail;
    private TextView tvChangePassword;
    private TextView tvAddressMange;
    private TextView tvNameVerify;
    private TextView tvBtnLogout;
    private TextView tvSystemSetting;
    private int InputFlag = -1;
    private User userInfoBean ;

    @Override
    public int setView() {
        return R.layout.activity_setting;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        initLogic();
        requestData();
    }

    private void requestData() {
        UserInfoManger.fetch(new UserInfoManger.FetchUserInfoListener() {
            @Override
            public void success(User userInfo) {
                userInfoBean = userInfo;
                updateView();
            }
        });
    }

    private void updateView() {
        etEmail.setText(userInfoBean.getEmail());
        etPhonenumber.setText(userInfoBean.getMobile_phone());
        tvUsername.setText(userInfoBean.getUser_name());
        String s = "";
        if(userInfoBean.getSex() == 1){
            s+="男";
        }else if(userInfoBean.getSex() == 2){
            s+="女";
        }else{
            s+="保密";
        }
        tvSex.setText(s);
        Glide.with(mActivity).load(userInfoBean.getUser_picture()).dontAnimate().placeholder(R.drawable.placeholder).into(ivHeadimg);
    }

    private void initLogic() {
        ivHeadimg.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        llUsername.setOnClickListener(this);
        llSex.setOnClickListener(this);
        llPhonenumber.setOnClickListener(this);
        llEmail.setOnClickListener(this);
        tvChangePassword.setOnClickListener(this);
        tvAddressMange.setOnClickListener(this);
        tvNameVerify.setOnClickListener(this);
        tvBtnLogout.setOnClickListener(this);
        tvSystemSetting.setOnClickListener(this);

    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.ic_back);
        ivBack.setVisibility(View.VISIBLE);
        title = (TextView) findViewById(R.id.title);
        title.setText("账户设置");
        ivHeadimg = (CircleImageView)findViewById( R.id.iv_headimg );
        llUsername = (LinearLayout)findViewById( R.id.ll_username );
        tvUsername = (TextView)findViewById( R.id.tv_username );
        llSex = (LinearLayout)findViewById( R.id.ll_sex );
        tvSex = (TextView)findViewById( R.id.tv_sex );
        llPhonenumber = (LinearLayout)findViewById( R.id.ll_phonenumber );
        etPhonenumber = (TextView) findViewById( R.id.et_phonenumber );
        llEmail = (LinearLayout)findViewById( R.id.ll_email );
        etEmail = (TextView) findViewById( R.id.et_email );
        tvChangePassword = (TextView)findViewById( R.id.tv_change_password );
        tvAddressMange = (TextView)findViewById( R.id.tv_address_mange );
        tvNameVerify = (TextView)findViewById( R.id.tv_name_verify );
        tvBtnLogout = (TextView)findViewById( R.id.tv_btn_logout );
        tvSystemSetting = (TextView)findViewById( R.id.tv_setting );
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_headimg:
                MultiImageSelector.create().showCamera(true).single().start(this,666);
                break;
            case R.id.ic_back:
                finish();
                break;
            case R.id.ll_email:
                InputFlag = 0;
                showInputDialog("你正在修改邮箱地址...");
                break;
            case R.id.ll_phonenumber:
                InputFlag = 1;
                showInputDialog("你正在修改手机号码...");
                break;
            case R.id.ll_username:
                break;
            case R.id.ll_sex:
                showSexPicker();
                break;
            case R.id.tv_address_mange:
                startActivity(new Intent(this,AddressListActivity.class));
                break;
            case R.id.tv_change_password:
                startActivity(new Intent(this,ResetPasswordActivity.class));
                break;
            case R.id.tv_name_verify:
                startActivity(new Intent(this,NameVerifyActivity.class));
                break;
            case R.id.tv_btn_logout:
                SPUtil.saveDate(this, Const.IsLogin,false);
                Const.isLogin = false;
                App.finishAllActivity();
                startActivity(new Intent(this,MainActivity.class));
                break;
            case R.id.tv_setting:
                startActivity(new Intent(this,SystemSettingActivity.class));
                break;
        }
    }

    private void showSexPicker() {
        final List<String> op1 = new ArrayList<>();

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                userInfoBean.setSex(options1);
                changeInfoRequest();
            }
        }).setTitleText("性别")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x00000000) //设置外部遮罩颜色
                .build();
        op1.add("保密");
        op1.add("男");
        op1.add("女");
        pvOptions.setPicker(op1);
        pvOptions.show();
    }

    private void showInputDialog(final String s) {
       final NiceDialog tempDialog = NiceDialog.init();

       tempDialog.setLayoutId(R.layout.commit_layout)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.setText(R.id.tv_title,s);
                        final EditText editText = (EditText) holder.getView(R.id.edit_input);
                        editText.post(new Runnable() {
                            @Override
                            public void run() {
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.showSoftInput(editText, 0);
                            }
                        });
                        holder.setOnClickListener(R.id.tv_cancel_edit, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                tempDialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.tv_confirm_edit, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                String input = editText.getText().toString();
                                if (TextUtils.isEmpty(input)) {
                                    ToastUtil.showToast("输入点什么再确定吧！");
                                }else {
                                    if(InputFlag == -1){
                                        return;
                                    }else if(InputFlag == 0){
                                        userInfoBean.setEmail(input);
                                    }else if(InputFlag == 1){
                                        userInfoBean.setMobile_phone(input);
                                    }
                                    InputFlag = -1;
                                    tempDialog.dismiss();
                                    changeInfoRequest();
                                }
                            }
                        });
                    }
                })
                .setOutCancel(false)
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private void changeInfoRequest() {
        UserInfoManger.updateInfo(userInfoBean, new UserInfoManger.FetchUserInfoListener() {
            @Override
            public void success(User userInfo) {
                userInfoBean = userInfo;
                updateView();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == 666){
                ArrayList<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                if(list.size()!=0){
                    UserInfoManger.updateAvatar(list.get(0), new UserInfoManger.UploadAvatarListener() {
                        @Override
                        public void success(String url) {
                            userInfoBean.setUser_picture(url);
                            updateView();
                        }
                    },this);
                }
            }
        }
    }
}
